package cn.lvji.sus.filter;

import cn.lvji.sus.GetSPIMaps;
import cn.lvji.sus.Config;
import cn.lvji.sus.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 长短链接转换filter
 *
 * @author zhouzx
 */
@WebFilter(filterName = "myFilter", urlPatterns = "/*", description = "短链filter")
public class MyFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);
    private static final List<String> NO_MAPS = Arrays.asList("index.jsp", "create");

    private Maps urlMaps;

    @Override
    public void init(FilterConfig filterConfig) {
        //检查配置
        Config.getConfig("db.url");
        this.urlMaps = GetSPIMaps.getMaps();
        logger.info("初始化filter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUrl = request.getRequestURI().replaceFirst(request.getContextPath() + "/", "");
        if (NO_MAPS.contains(requestUrl) || requestUrl.endsWith(".png")) {
            chain.doFilter(request, response);
            return;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("receive a request {}", requestUrl);
        }
        String shortUrl = urlMaps.maps(requestUrl);
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", shortUrl);
    }

    @Override
    public void destroy() {
        logger.warn("filter销毁中。。。。。。。");
    }
}
